package com.iplant.aps.serviceimpl.dao.oms;

import com.iplant.aps.service.mesenum.MESDBSource;
import com.iplant.aps.service.mesenum.MESException;
import com.iplant.aps.service.mesenum.OMSCheckType;
import com.iplant.aps.service.po.OutResult;
import com.iplant.aps.service.po.ServiceResult;
import com.iplant.aps.service.po.bms.BMSEmployee;
import com.iplant.aps.service.po.oms.OMSCheckMsg;
import com.iplant.aps.service.utils.StringUtils;
import com.iplant.aps.serviceimpl.dao.BaseDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import java.text.MessageFormat;
import java.util.*;

public class OMSCheckMsgDAO extends BaseDAO {

    private static final Logger logger = LoggerFactory.getLogger(OMSCheckMsgDAO.class);

    private static OMSCheckMsgDAO Instance = null;

    private OMSCheckMsgDAO() {
        super();
    }

    public static OMSCheckMsgDAO getInstance() {
        if (Instance == null)
            Instance = new OMSCheckMsgDAO();
        return Instance;
    }

    /**
     * 添加或修改
     */
    public int Update(BMSEmployee wLoginUser, OMSCheckMsg wOMSCheckMsg, OutResult<Integer> wErrorCode) {
        int wResult = 0;
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser.getCompanyID(), MESDBSource.Basic,
                    wLoginUser.getID(), 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResult;
            }

            if (wOMSCheckMsg == null)
                return 0;

            String wSQL = "";
            if (wOMSCheckMsg.getID() <= 0) {
                wSQL = MessageFormat.format("INSERT INTO {0}.oms_checkmsg(Type,Message,ProductNo,LineName,PartName," +
                                "PartPointName,PartNo,DutyPerson,CloseTime,PlanTaskID,CreateID,CreateTime,EditID," +
                                "EditTime) VALUES(:Type,:Message,:ProductNo,:LineName,:PartName,:PartPointName," +
                                ":PartNo,:DutyPerson,:CloseTime,:PlanTaskID,:CreateID,:CreateTime,:EditID,:EditTime);",
                        wInstance.Result);
            } else {
                wSQL = MessageFormat.format("UPDATE {0}.oms_checkmsg SET Type = :Type,Message = :Message,ProductNo = " +
                                ":ProductNo,LineName = :LineName,PartName = :PartName,PartPointName = :PartPointName," +
                                "PartNo = :PartNo,DutyPerson = :DutyPerson,CloseTime = :CloseTime,PlanTaskID = " +
                                ":PlanTaskID,CreateID = :CreateID,CreateTime = :CreateTime,EditID = :EditID,EditTime " +
                                "= :EditTime WHERE ID = :ID;",
                        wInstance.Result);
            }

            wSQL = this.DMLChange(wSQL);

            Map<String, Object> wParamMap = new HashMap<String, Object>();

            wParamMap.put("ID", wOMSCheckMsg.ID);
            wParamMap.put("Type", wOMSCheckMsg.Type);
            wParamMap.put("Message", wOMSCheckMsg.Message);
            wParamMap.put("ProductNo", wOMSCheckMsg.ProductNo);
            wParamMap.put("LineName", wOMSCheckMsg.LineName);
            wParamMap.put("PartName", wOMSCheckMsg.PartName);
            wParamMap.put("PartPointName", wOMSCheckMsg.PartPointName);
            wParamMap.put("PartNo", wOMSCheckMsg.PartNo);
            wParamMap.put("DutyPerson", wOMSCheckMsg.DutyPerson);
            wParamMap.put("CloseTime", wOMSCheckMsg.CloseTime);
            wParamMap.put("PlanTaskID", wOMSCheckMsg.PlanTaskID);
            wParamMap.put("CreateID", wOMSCheckMsg.CreateID);
            wParamMap.put("CreateTime", wOMSCheckMsg.CreateTime);
            wParamMap.put("EditID", wOMSCheckMsg.EditID);
            wParamMap.put("EditTime", wOMSCheckMsg.EditTime);

            KeyHolder keyHolder = new GeneratedKeyHolder();
            SqlParameterSource wSqlParameterSource = new MapSqlParameterSource(wParamMap);

            shrisJdbcTemplate.update(wSQL, wSqlParameterSource, keyHolder);

            if (wOMSCheckMsg.getID() <= 0) {
                wResult = Objects.requireNonNull(keyHolder.getKey()).intValue();
                wOMSCheckMsg.setID(wResult);
            } else {
                wResult = wOMSCheckMsg.getID();
            }
        } catch (Exception ex) {
            wErrorCode.set(MESException.DBSQL.getValue());
            logger.error(ex.toString());
        }
        return wResult;
    }

    /**
     * 删除集合
     */
    public ServiceResult<Integer> DeleteList(BMSEmployee wLoginUser, List<OMSCheckMsg> wList,
                                             OutResult<Integer> wErrorCode) {
        ServiceResult<Integer> wResult = new ServiceResult<Integer>(0);
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser.getCompanyID(), MESDBSource.Basic,
                    wLoginUser.getID(), 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResult;
            }

            if (wList == null || wList.size() <= 0)
                return wResult;

            List<String> wIDList = new ArrayList<String>();
            for (OMSCheckMsg wItem : wList) {
                wIDList.add(String.valueOf(wItem.ID));
            }
            String wSql = MessageFormat.format("delete from {1}.oms_checkmsg WHERE ID IN({0}) ;",
                    String.join(",", wIDList), wInstance.Result);
            this.ExecuteSqlTransaction(wSql);
        } catch (Exception ex) {
            wErrorCode.set(MESException.DBSQL.getValue());
            logger.error(ex.toString());
        }
        return wResult;
    }

    /**
     * 查单条
     */
    public OMSCheckMsg SelectByID(BMSEmployee wLoginUser, int wID, OutResult<Integer> wErrorCode) {
        OMSCheckMsg wResult = new OMSCheckMsg();
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser.getCompanyID(), MESDBSource.Basic,
                    wLoginUser.getID(), 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResult;
            }

            List<OMSCheckMsg> wList = SelectList(wLoginUser, wID, -1, -1, wErrorCode);
            if (wList == null || wList.size() != 1)
                return wResult;
            wResult = wList.get(0);
        } catch (Exception e) {
            wErrorCode.set(MESException.DBSQL.getValue());
            logger.error(e.toString());
        }
        return wResult;
    }

    /**
     * 条件查询集合
     */
    public List<OMSCheckMsg> SelectList(BMSEmployee wLoginUser, int wID, int wType, int wPlanTaskID,
                                        OutResult<Integer> wErrorCode) {
        List<OMSCheckMsg> wResultList = new ArrayList<OMSCheckMsg>();
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser.getCompanyID(), MESDBSource.Basic,
                    wLoginUser.getID(), 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResultList;
            }

            String wSQL = MessageFormat.format(
                    "SELECT t.*,t1.Name Creator,t2.Name Editor FROM {0}.oms_checkmsg t"
                            + " left join {0}.mbs_user t1 on t.CreateID=t1.ID "
                            + " left join {0}.mbs_user t2 on t.EditID=t2.ID "
                            + "WHERE  1=1  " +
                            "and ( :wID <= 0 or :wID = t.ID ) " +
                            "and ( :wType <= 0 or :wType = t.Type ) " +
                            "and ( :wPlanTaskID <= 0 or :wPlanTaskID = t.PlanTaskID );",
                    wInstance.Result);

            Map<String, Object> wParamMap = new HashMap<String, Object>();

            wParamMap.put("wID", wID);
            wParamMap.put("wType", wType);
            wParamMap.put("wPlanTaskID", wPlanTaskID);

            wSQL = this.DMLChange(wSQL);

            List<Map<String, Object>> wQueryResult = shrisJdbcTemplate.queryForList(wSQL, wParamMap);

            for (Map<String, Object> wReader : wQueryResult) {
                OMSCheckMsg wItem = new OMSCheckMsg();

                wItem.ID = StringUtils.parseInt(wReader.get("ID"));
                wItem.Type = StringUtils.parseInt(wReader.get("Type"));
                wItem.TypeText = OMSCheckType.getEnumType(wItem.Type).getLable();
                wItem.Message = StringUtils.parseString(wReader.get("Message"));
                wItem.ProductNo = StringUtils.parseString(wReader.get("ProductNo"));
                wItem.LineName = StringUtils.parseString(wReader.get("LineName"));
                wItem.PartName = StringUtils.parseString(wReader.get("PartName"));
                wItem.PartPointName = StringUtils.parseString(wReader.get("PartPointName"));
                wItem.PartNo = StringUtils.parseString(wReader.get("PartNo"));
                wItem.DutyPerson = StringUtils.parseString(wReader.get("DutyPerson"));
                wItem.CloseTime = StringUtils.parseCalendar(wReader.get("CloseTime"));
                wItem.PlanTaskID = StringUtils.parseInt(wReader.get("PlanTaskID"));
                wItem.CreateID = StringUtils.parseInt(wReader.get("CreateID"));
                wItem.Creator = StringUtils.parseString(wReader.get("Creator"));
                wItem.CreateTime = StringUtils.parseCalendar(wReader.get("CreateTime"));
                wItem.EditID = StringUtils.parseInt(wReader.get("EditID"));
                wItem.Editor = StringUtils.parseString(wReader.get("Editor"));
                wItem.EditTime = StringUtils.parseCalendar(wReader.get("EditTime"));

                wResultList.add(wItem);
            }
        } catch (Exception ex) {
            wErrorCode.set(MESException.DBSQL.getValue());
            logger.error(ex.toString());
        }
        return wResultList;
    }
}
